import { OnInit, Component, Input, Output, EventEmitter, OnChanges } from '@angular/core';
import { UploadFile, UploadFilter, NzMessageService } from 'ng-zorro-antd';
import { SystemFileService } from 'src/app/project/service/icm/icm-global/system-file/system-file.service';
import { SystemFileDTO } from 'src/app/project/model/icm/icm-global/system-file/system-file-dto';

@Component({
  selector: 'app-attach-small',
  templateUrl: './attach-small.component.html',
  styles: [],
})
export class AttachSmallComponent implements OnInit, OnChanges {
  /**
   * 组件的实例，因为转换base回调onload事件目前无法访问this
   * 在路由复用的场景下，不确定会不会有问题, 目前未发现
   */
  static attachSmallComponent: AttachSmallComponent = null;

  constructor(private msg: NzMessageService, private systemFileService: SystemFileService) {
    AttachSmallComponent.attachSmallComponent = this;
  }

  /**
   * 组件可见性
   */
  @Input()
  isVisible = false;

  /**
   * 按钮可见性
   */
  @Input()
  isShow = true;

  /**
   * 上传文件列表
   */
  fileList: UploadFile[] = [];

  /**
   * 初始化图片
   */
  previewImage: string | undefined = '';

  /**
   * 预览文件
   */
  previewFile: string | undefined = '';

  /**
   * 预览窗口
   */
  previewVisible = false;

  /**
   * 按钮状态控制
   */
  uploading = false;

  /**
   * 功能模块标识类型（固定值，是指功能模块名）
   */
  @Input()
  attachType: string;

  /**
   * 是否只读
   */
  @Input()
  readOnly = false;

  /**
   * 加载
   */
  loading: boolean;

  /**
   * 附件列表
   */
  @Input()
  attachFiles: Array<SystemFileDTO> = [
    {
      name: '',
      originalName: '',
      size: 0,
      type: '',
      id: '',
    },
  ];
  // tslint:disable-next-line: no-output-native
  @Output()
  result = new EventEmitter();

  /**
   * 文件上传 类型限制
   */
  @Input()
  filters: UploadFilter[] = [
    {
      name: 'type',
      fn: (fileList: UploadFile[]) => {
        // tslint:disable-next-line: no-bitwise
        const fileType = 'exe,jsp,asp,html,xml';
        const filterFiles = [];
        fileList.forEach(f => {
          const suffix = f.name.slice(f.name.lastIndexOf('.') + 1);
          if (!fileType.includes(suffix)) {
            filterFiles.push(f);
          }
        });

        if (filterFiles.length !== fileList.length) {
          this.msg.error(`包含上传不支持的文件格式`);
          return filterFiles;
        }

        return fileList;
      },
    },
  ];

  /**
   * 删除附件
   * @param data 需要删除的附件数据
   *
   */
  deleteAttach(data: any) {
    this.attachFiles = this.attachFiles.filter(item => item !== data);
    this.result.emit(this.attachFiles);
  }

  /**
   * 取消事件
   */
  handleCancel() {
    // 清空上传文件列表
    // if (!this.readOnly) {
    //   this.fileList = [];
    //   this.attachFiles = [];
    // }
    this.isVisible = false;
  }

  /**
   * 查看后不做任何操作并返回
   */
  back() {
    this.isVisible = false;
  }

  /**
   * 选取上传文件，添加文件到上传列表
   *
   */
  beforeUpload = (file: UploadFile): boolean => {
    this.fileList = this.fileList.concat(file);
    return false;
    // tslint:disable-next-line: semicolon
  };

  /**
   * 上传文件
   */
  handleUpload(): void {
    const formData = new FormData();
    this.fileList.forEach((file: any) => {
      formData.append('files', file);
    });
    this.uploading = true;

    this.systemFileService.uploadMultipleFiles(formData, this.attachType).subscribe(res => {
      const list = this.constructAttchObject(res);
      this.attachFiles = this.attachFiles.concat(list);
    });
    this.fileList = [];
    this.uploading = false;
  }

  /**
   * 构造附件对象
   */
  constructAttchObject(files: SystemFileDTO[]): SystemFileDTO[] {
    // tslint:disable-next-line: only-arrow-functions
    return files.map(function(item) {
      return {
        name: item.name,
        originalName: item.originalName,
        size: item.size,
        type: item.type,
        id: item.id,
      };
    });
  }

  /**
   * 将文件信息弹射回附件管理组件
   */
  save() {
    this.result.emit(this.attachFiles);
    this.handleCancel();
  }

  /**
   * 下载文件
   */
  download(id: string, originalName: string) {
    this.loading = true;
    // tslint:disable-next-line: deprecation
    this.systemFileService.downloadFileContentById(id).subscribe(
      blob => {
        const uA = window.navigator.userAgent; // 判断浏览器内核
        const isIE =
          /msie\s|trident\/|edge\//i.test(uA) &&
          !!(
            'uniqueID' in document ||
            'documentMode' in document ||
            'ActiveXObject' in window ||
            'MSInputMethodContext' in window
          );
        const binaryData = [];
        binaryData.push(blob.body);
        const objectUrl = window.URL.createObjectURL(new Blob(binaryData, { type: blob.body.type }));
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.href = objectUrl;
        a.download = originalName ? originalName : '';
        if (isIE) {
          // 兼容IE11无法触发下载的问题
          navigator.msSaveBlob(new Blob(binaryData), a.download);
        } else {
          a.click();
        }
        a.remove();
      },
      null,
      () => {
        this.loading = false;
      },
    );
  }

  /**
   * 预览
   */
  preview(id: string, fileNname?: string) {
    const fileType = 'png,jpg,jpeg';
    const suffix = fileNname.slice(fileNname.lastIndexOf('.') + 1);

    if (fileType.includes(suffix)) {
      // 预览图片
      this.systemFileService.getFileContentById(id).subscribe(
        blob => {
          const binaryData = [];
          binaryData.push(blob.body);

          const objectUrl = window.URL.createObjectURL(new Blob(binaryData, { type: blob.body.type }));
          window.open(objectUrl);
          // const a = new FileReader();
          // a.readAsDataURL(blob.body);
          // // tslint:disable-next-line: only-arrow-functions
          // a.onload = function(e) {
          //   // tslint:disable-next-line: no-string-literal
          //   if (typeof e.target['result'] === 'string') {
          //     // tslint:disable-next-line:no-string-literal
          //     AttachSmallComponent.attachSmallComponent.previewImage = e.target['result'];
          //     AttachSmallComponent.attachSmallComponent.previewVisible = true;
          //   }
          // };
        },
        () => {},
        null,
      );
    } else {
      this.systemFileService.previewFileById(id).subscribe(
        blob => {
          const uA = window.navigator.userAgent; // 判断浏览器内核
          const isIE =
            /msie\s|trident\/|edge\//i.test(uA) &&
            !!(
              'uniqueID' in document ||
              'documentMode' in document ||
              'ActiveXObject' in window ||
              'MSInputMethodContext' in window
            );
          const binaryData = [];
          binaryData.push(blob.body);
          const objectUrl = window.URL.createObjectURL(new Blob(binaryData, { type: blob.body.type }));
          window.open(objectUrl);
        },
        () => {},
        null,
      );
    }
  }

  ngOnInit() {
    if (!this.attachFiles) {
      this.attachFiles = [];
    }
  }

  ngOnChanges() {
    if (!this.attachFiles) {
      this.attachFiles = [];
    }
  }
}
